package org.zyj.io.example.case4;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class HeatBeatServer {

    private final int port;

    public HeatBeatServer(int port) {
        this.port = port;
    }

    public void run() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(8);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)//
                    .channel(NioServerSocketChannel.class)//
                    .option(ChannelOption.SO_BACKLOG, 128)//
                    .option(ChannelOption.SO_KEEPALIVE, true)//
                    .handler(new LoggingHandler(LogLevel.INFO))//netty提供的日志处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            var pipeline = ch.pipeline();
                            /*
                            Netty提供的空闲检测handler
                            构造函数的入参:
                             1. readerIdleTime: 表示多长时间没有读, 就会发送一个心跳检测包检测是否连接
                             2. writerIdleTime: 表示多长时间没有写, 就会发送一个心跳检测包检测是否连接
                             3. allIdleTime: 表示多长时间没有读写, 就会发送一个心跳检测包检测是否连接

                             Triggers an IdleStateEvent when a Channel has not performed read, write, or both operation for a while. Supported idle states
                             ---
                             当 IdleStateEvent 触发后, 就会传递给管道的下一个 handler 去处理
                             通过调用(触发) 下一个handler的userEventTrigger, 在该方法中去处理IdleStateEvent
                             */
                            //因为只要有读写任务, 就要从pipeline上的 IdleStateHandler 过一遍, 所以这个一定能检测到是否读写, 但是他并不知道是否写到了客户端, 它仅仅只知道服务端这的情况
                            pipeline.addLast(new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));

                            //加一个对空闲检测进一步处理的handler(自定义)
                            //在这里就可以 自定义的 心跳包处理了
                            pipeline.addLast(new MyHeatBeatHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    System.out.println("服务器启动: 端口监听成功");
                } else {
                    System.out.println("服务器启动: 端口监听失败");
                }
            });
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new HeatBeatServer(7527).run();
    }
}
